﻿using System.IO;
using System.Text;

namespace TestWcfRestService
{
    public class ResponseFilterStream : Stream
    {
        private Stream OriginalResponseFilter;
        private StringBuilder ResponseOutputCache;
        private Encoding ResponseContentEncoding;

        public ResponseFilterStream(Stream originalResponseFilter, Encoding encoding)
        {
            OriginalResponseFilter = originalResponseFilter;
            ResponseOutputCache = new StringBuilder(512 * 1024); //default capacity 512kb
            ResponseContentEncoding = encoding;
        }

        #region -= useless overrides =-
        public override bool CanRead
        {
            get { return true; }
        }

        public override bool CanSeek
        {
            get { return true; }
        }

        public override bool CanWrite
        {
            get { return false; }
        }

        public override long Length
        {
            get { return OriginalResponseFilter.Length; }
        }

        private long? _Position;
        public override long Position
        {
            get { return null == _Position ? OriginalResponseFilter.Length : _Position.Value; }
            set { _Position = value; }
        }

        public override void Flush()
        {
            OriginalResponseFilter.Flush();
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            return OriginalResponseFilter.Read(buffer, offset, count);
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            return OriginalResponseFilter.Seek(offset, origin);
        }

        public override void SetLength(long value)
        {
            OriginalResponseFilter.SetLength(value);
        }
        #endregion

        public override void Write(byte[] buffer, int offset, int count)
        {
            var s = ResponseContentEncoding.GetString(buffer, offset, count);
            ResponseOutputCache.Append(s);
            OriginalResponseFilter.Write(buffer, offset, buffer.Length);
        }

        public string GetResponseOutput()
        {
            return ResponseOutputCache.ToString();
        }
    }
}
